package mq

import (
	"context"

	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/mq"
)

func (m *MQ) SubscribeReport(ctx context.Context, reportID uint, body chan<- []byte) error {
	ch, q, err := m.DeclareQueue(mq.QueueDeclareConfig{Exclusive: true, AutoDelete: true})
	if err != nil {
		return err
	}

	if err := m.QueueBindWithChannel(ch, mq.QueueBindConfig{
		Name:     q.Name,
		Key:      getReportPublishRouterKey(reportID),
		Exchange: reportPublishExchange,
	}); err != nil {
		return err
	}

	if err := m.RegisterDeclaredQueueConsumer(
		ch,
		mq.ConsumerConfig{Ctx: ctx,  Queue: q.Name, AutoAck: false},
		func(d *mq.Delivery) {
			select {
			case <-ctx.Done():
			case body <- d.Body:
			}

			d.Ack(false)
			if err := ch.Close(); err != nil {
				logger.Warn("SubscribeReport: close channel", err)
			}
			logger.Debug("SubscribeReport: close channel")
		},
	); err != nil {
		ch.Close()
		return err
	}

	return nil
}
